package com.example.cemenghuii.service;

import com.example.cemenghuii.entity.Meeting;
import com.example.cemenghuii.entity.MeetingRegistration;
import com.example.cemenghuii.mapper.MeetingMapper;
import com.example.cemenghuii.mapper.MeetingRegistrationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MeetingService {

    @Autowired
    private MeetingMapper meetingMapper;

    @Autowired
    private MeetingRegistrationMapper registrationMapper;

    /**
     * 根据ID查询会议
     */
    public Meeting getMeetingById(Long id) {
        return meetingMapper.selectById(id);
    }

    /**
     * 创建会议
     */
    public boolean createMeeting(Meeting meeting) {
        meeting.setCreateTime(LocalDateTime.now());
        meeting.setUpdateTime(LocalDateTime.now());
        meeting.setRegistrationCount(0);

        // 企业用户创建的会议需要审核
        if (meeting.getCreatorId() != null) {
            meeting.setStatus(0); // 待审核
        } else {
            meeting.setStatus(1); // 管理员创建直接通过
        }

        return meetingMapper.insert(meeting) > 0;
    }

    /**
     * 更新会议
     */
    public boolean updateMeeting(Meeting meeting) {
        meeting.setUpdateTime(LocalDateTime.now());
        return meetingMapper.update(meeting) > 0;
    }

    /**
     * 删除会议
     */
    @Transactional
    public boolean deleteMeeting(Long id) {
        // 先删除相关的报名记录
        registrationMapper.deleteByMeetingId(id);
        // 再删除会议
        return meetingMapper.deleteById(id) > 0;
    }

    /**
     * 分页查询会议列表
     */
    public Map<String, Object> getMeetingList(String meetingName, String meetingType, String creatorName,
                                              Integer status, Long creatorId, LocalDateTime startDate,
                                              LocalDateTime endDate, Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;
        List<Meeting> meetingList = meetingMapper.selectMeetingList(meetingName, meetingType, creatorName,
                status, creatorId, startDate, endDate, offset, pageSize);
        int total = meetingMapper.countMeetings(meetingName, meetingType, creatorName,
                status, creatorId, startDate, endDate);

        Map<String, Object> result = new HashMap<>();
        result.put("list", meetingList);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("totalPages", (total + pageSize - 1) / pageSize);

        return result;
    }

    /**
     * 审核会议
     */
    public boolean auditMeeting(Long id, Integer status) {
        Meeting meeting = meetingMapper.selectById(id);
        if (meeting == null) {
            throw new RuntimeException("会议不存在");
        }

        return meetingMapper.updateStatus(id, status) > 0;
    }

    /**
     * 获取待审核会议列表
     */
    public Map<String, Object> getPendingMeetingList(Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;
        List<Meeting> meetingList = meetingMapper.selectPendingMeetings(offset, pageSize);
        int total = meetingMapper.countPendingMeetings();

        Map<String, Object> result = new HashMap<>();
        result.put("list", meetingList);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("totalPages", (total + pageSize - 1) / pageSize);

        return result;
    }

    /**
     * 小程序端获取已发布会议列表
     */
    public Map<String, Object> getPublishedMeetingList(String keyword, String meetingType, Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;
        List<Meeting> meetingList = meetingMapper.selectPublishedMeetings(keyword, meetingType, offset, pageSize);
        int total = meetingMapper.countPublishedMeetings(keyword, meetingType);

        Map<String, Object> result = new HashMap<>();
        result.put("list", meetingList);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("totalPages", (total + pageSize - 1) / pageSize);

        return result;
    }

    /**
     * 根据用户ID查询会议列表
     */
    public Map<String, Object> getMeetingByCreatorId(Long creatorId, Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;
        List<Meeting> meetingList = meetingMapper.selectByCreatorId(creatorId, offset, pageSize);
        int total = meetingMapper.countByCreatorId(creatorId);

        Map<String, Object> result = new HashMap<>();
        result.put("list", meetingList);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("totalPages", (total + pageSize - 1) / pageSize);

        return result;
    }

    /**
     * 根据会议类型查询会议列表
     */
    public Map<String, Object> getMeetingByType(String meetingType, Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;
        List<Meeting> meetingList = meetingMapper.selectByMeetingType(meetingType, offset, pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("list", meetingList);
        result.put("page", page);
        result.put("pageSize", pageSize);

        return result;
    }

    /**
     * 获取即将开始的会议
     */
    public Map<String, Object> getUpcomingMeetings(Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;
        LocalDateTime currentTime = LocalDateTime.now();
        List<Meeting> meetingList = meetingMapper.selectUpcomingMeetings(currentTime, offset, pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("list", meetingList);
        result.put("page", page);
        result.put("pageSize", pageSize);

        return result;
    }

    /**
     * 会议报名
     */
    @Transactional
    public boolean registerMeeting(MeetingRegistration registration) {
        // 检查是否已经报名
        MeetingRegistration existing = registrationMapper.selectByMeetingIdAndOpenId(
                registration.getMeetingId(), registration.getOpenId());
        if (existing != null) {
            throw new RuntimeException("您已经报名过该会议");
        }

        // 检查手机号是否已报名
        MeetingRegistration existingByPhone = registrationMapper.selectByMeetingIdAndPhone(
                registration.getMeetingId(), registration.getPhone());
        if (existingByPhone != null) {
            throw new RuntimeException("该手机号已经报名过该会议");
        }

        // 获取会议信息
        Meeting meeting = meetingMapper.selectById(registration.getMeetingId());
        if (meeting == null) {
            throw new RuntimeException("会议不存在");
        }
        if (meeting.getStatus() != 1) {
            throw new RuntimeException("会议未发布或已结束");
        }

        registration.setMeetingName(meeting.getMeetingName());
        registration.setCreateTime(LocalDateTime.now());

        // 保存报名记录
        boolean result = registrationMapper.insert(registration) > 0;
        if (result) {
            // 增加报名人数
            meetingMapper.incrementRegistrationCount(registration.getMeetingId());
        }

        return result;
    }

    /**
     * 取消报名
     */
    @Transactional
    public boolean cancelRegistration(Long meetingId, String openId) {
        MeetingRegistration registration = registrationMapper.selectByMeetingIdAndOpenId(meetingId, openId);
        if (registration == null) {
            throw new RuntimeException("未找到报名记录");
        }

        boolean result = registrationMapper.deleteById(registration.getId()) > 0;
        if (result) {
            // 减少报名人数
            meetingMapper.decrementRegistrationCount(meetingId);
        }

        return result;
    }

    /**
     * 获取会议报名列表
     */
    public Map<String, Object> getMeetingRegistrations(Long meetingId, Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;
        List<MeetingRegistration> registrations = registrationMapper.selectByMeetingId(meetingId, offset, pageSize);
        int total = registrationMapper.countByMeetingId(meetingId);

        Map<String, Object> result = new HashMap<>();
        result.put("list", registrations);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("totalPages", (total + pageSize - 1) / pageSize);

        return result;
    }

    /**
     * 检查用户是否有权限操作该会议
     */
    public boolean checkMeetingPermission(Long meetingId, Long userId, Integer userType) {
        // 超级管理员可以操作所有会议
        if (userType == 2) {
            return true;
        }

        // 企业用户只能操作自己创建的会议
        Meeting meeting = meetingMapper.selectById(meetingId);
        return meeting != null && meeting.getCreatorId().equals(userId);
    }

    /**
     * 检查用户是否已报名会议
     */
    public boolean checkUserRegistration(Long meetingId, String openId) {
        MeetingRegistration registration = registrationMapper.selectByMeetingIdAndOpenId(meetingId, openId);
        return registration != null;
    }
}